import { i18n } from '@app-nextmesh/common/utils';
import ArboristTree from '@app-nextmesh/components/Tree';
import {
  IMenuItem,
  ITreeNode,
  ITreeProps,
  TreeNodeMenuId,
  ValueMenuSeparator,
} from '@app-nextmesh/components/types';
import { useEffect, useState } from 'react';
import { contextMenu, Item, Menu, Separator } from 'react-contexify';
import { createPortal } from 'react-dom';
import { makeComponentMenuItems } from './ComponentMenu';
import LeftTreeData from './data';
import { makeSimuConditionMenuItems } from './SimulationMenus';

const DynamicMenuId = 'dynamic_menu';
export default function Tree({
  treeData,
  initActive,
  onMenuItemClick,
  onTreeNodeClick,
  onTreeNodeDoubleClick,
  readonly,
}: ITreeProps) {
  const [active, setActive] = useState<ITreeNode | null>(null);
  const [dynamicMenuItems, setDynamicMenuItems] = useState<IMenuItem[]>([]);

  useEffect(() => {
    setActive(initActive);
  }, [initActive]);
  const handleNodeClick = (node: ITreeNode) => {
    onTreeNodeClick?.(node);
  };
  const showContextMenu = (e, treeNode: ITreeNode) => {
    if (readonly) {
      return;
    }
    let items: IMenuItem[] = [];
    const menuId = treeNode.menuId;
    if (!menuId) {
      items = [];
    } else {
      items = LeftTreeData.menuData.find((menu) => menu.id === menuId)?.items;
      if (!items) {
        // 判断menuId，动态生成菜单
        if (menuId === TreeNodeMenuId.component) {
          // 仿真分组
          items = makeComponentMenuItems(treeNode.formData);
        } else if (menuId.startsWith(TreeNodeMenuId.simuCondition)) {
          // 仿真条件
          items = makeSimuConditionMenuItems(menuId);
        }
      }
    }
    setDynamicMenuItems(items || []);
    contextMenu.show({
      id: DynamicMenuId,
      event: e,
      props: treeNode,
    });
    e.preventDefault();
    e.stopPropagation();
  };
  const makeItems = (items: IMenuItem[]) => {
    return items.map((item) =>
      item.value === ValueMenuSeparator ? (
        <Separator key={item.value} />
      ) : (
        <Item
          id={item.value}
          key={item.value}
          data={item}
          onClick={({ props, data }) => onMenuItemClick(props, data)}>
          {i18n.t(item.label) || item.label}
        </Item>
      ),
    );
  };
  return (
    <>
      <ArboristTree
        initialData={treeData}
        onContextMenu={(event, node) => {
          showContextMenu(event, node);
        }}
        onActivate={(node) => {
          handleNodeClick(node);
        }}
        onDoubleClick={onTreeNodeDoubleClick}
        selection={active?.id}
      />
      <div>
        {createPortal(
          <Menu
            style={{ display: dynamicMenuItems.length > 0 ? 'block' : 'none' }}
            id={DynamicMenuId}>
            {makeItems(dynamicMenuItems)}
          </Menu>,
          document.body,
        )}
      </div>
    </>
  );
}
